<?php

class WeixinController extends Controller
{
    public $layout = 'column1';
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}

	/**
	 * login by weixin id
	 */
	public function actionLogin()
	{
		$openid = Yii::app()->request->getParam('openid');
        if (Controller::isNullOrEmptyString($openid)) {
            return;
        }
        
        $userInfo = $this->getUserInfo($openid);
        if (!$userInfo || Controller::isNullOrEmptyString($userInfo)) {
            //echo 'userinfo null: '.'http://lizhao.net/weixin/main.php?command=getUserBasicInfo&openid='.$openid;
            return;
        }
        
        $userInfoObj = json_decode($userInfo);

        $user = User::model()->getUserByOpenId($openid, $userInfoObj->{"nickname"});
        if ($user != null) {
            $identity = new UserIdentity($user->username, $user->password);
            $identity->authenticate();
            
			Yii::app()->user->login($identity);
            
            $this->redirect(Yii::app()->user->returnUrl);
		}
	}
    
    public function getUserInfo($openid)
    {
        return Controller::sendRequest('http://lizhao.net/weixin/main.php?command=getUserBasicInfo&openid='.$openid,
                    '', 'testlizhao.net');
    }
}